/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.selectQuestion;

import javax.inject.Inject;

import ru.irenproject.Action;
import ru.irenproject.Utils;
import ru.irenproject.Visual;
import ru.irenproject.pad.PadEditor;
import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.AspectId;
import ru.irenproject.store.Event;
import ru.irenproject.store.Initializer;
import ru.irenproject.store.Stash;
import ru.irenproject.store.Thing;

import com.google.protobuf.Message;

public final class SelectQuestionChoiceEditor extends AbstractThing implements Visual {
  public static final class SetFixedInput {
    public boolean fixed;
  }

  public static final class SetCorrectInput {
    public boolean correct;
  }

  private static final AspectId ASPECT_ID = new AspectId(0x6d85d68372caac9eL);

  public static SelectQuestionChoiceEditor open(final SelectQuestionChoice choice) {
    return Utils.requireAspect(choice, ASPECT_ID, SelectQuestionChoiceEditor.class,
        new Initializer<SelectQuestionChoiceEditor>() {
      @Override public void initialize(SelectQuestionChoiceEditor target) {
        target.prepare(choice);
      }
    });
  }

  @Stash private SelectQuestionProtos.SelectQuestionChoiceEditor.Builder $;

  @Inject SelectQuestionChoiceEditor() {}

  private void prepare(SelectQuestionChoice choice) {
    $.setChoice(choice.id())
     .setPadEditor(PadEditor.create(choice.pad()).id());
    choice.addListener(this);
  }

  public SelectQuestionChoice choice() {
    return get($.getChoice(), SelectQuestionChoice.class);
  }

  @Action public void doSetFixed(SetFixedInput in) {
    choice().setFixed(in.fixed);
  }

  @Action public void doSetCorrect(SetCorrectInput in) {
    choice().setCorrect(in.correct);
  }

  @Override public Message render() {
    SelectQuestionChoice c = choice();
    return SelectQuestionProtos.SelectQuestionChoiceEditorShape.newBuilder()
        .setPadEditor($.getPadEditor())
        .setCorrect(c.correct())
        .setFixed(c.fixed())
        .setNegative(c.negative())
        .build();
  }

  @Override protected void handleEvent(Event e, Thing source) {
    if (e instanceof SelectQuestionChoice.ChangeEvent) {
      markForRender();
    }
  }
}
